package com.Policing.Check;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.Okhttps.HttpOkHttp;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Check_Item extends BaseActivity implements OnDismissListener {
    private ListView checklist;
    private TextView title_text;
    private Button submit;
    private Button scan_img;//扫码
    private ImageView fh;
    private EditText et_num;
    private List<String> data = new ArrayList<>();//上传的数据集合
    private List<Check_item_bean> check = new ArrayList<>();
    private String id="",roleId="",version="",routeId="",checkId="";
    private String url = "http://" + Ip_Set.IP + "/api/checkdetailQueryById2";
    private String urlup = "http://" + Ip_Set.IP + "/api/assetCheck2";
    @Override
    public int intiLayout() {
        return R.layout.polling_path;
    }

    @Override
    public void initView() {
        et_num = (EditText) findViewById(R.id.et_num);
        checklist = (ListView) findViewById(R.id.checklist);
        title_text = (TextView) findViewById(R.id.title_text);
        fh = (ImageView) findViewById(R.id.fh);
        scan_img = (Button) findViewById(R.id.scan_img);
        title_text.setText("不带标盘点");
        submit = (Button) findViewById(R.id.submit);
        fh.setOnClickListener(v -> finish());
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                et_num.selectAll();
                for (int i = 0; i<check.size();i++){
                    if (et_num.getText().toString().trim().equals(check.get(i).getAssetNumber())){
                        Toast.makeText(Check_Item.this, "您扫描的是"+check.get(i).getType()+",请填写实际数量", Toast.LENGTH_LONG).show();
                        checklist.setSelection(i);
                        return;
                    }
                }
                Toast.makeText(Check_Item.this, "此物资不在盘点计划中", Toast.LENGTH_LONG).show();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertView(" 提示！", "是否上传数据！！！", "取消",new String[]{"确定"}, null, Check_Item.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            for (int i =0;i<check.size();i++){
                                JSONObject root= new JSONObject();
                                try {
                                    root.put("id",check.get(i).getCheckdetailId());
                                    root.put("num",check.get(i).getRealitynum());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                data.add(root.toString());
                            }
                            upload();
                        }
                        if (position==-1){
                            return;
                        }
                    }
                }).setCancelable(true).setOnDismissListener(Check_Item.this).show();

            }
        });
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();

            }
        });
    }

    private void upload() {
        Map<String,String> map = new HashMap<>();
        map.put("checkId",checkId);
        map.put("userId",id);
        map.put("json",data.toString());
        map.put("source", Since_case.set().getSource());
        HttpOkHttp.getInstance().requestPost(urlup, map, new HttpOkHttp.OkHttpCallBack<String>() {

            @Override
            public void requestSuccess(final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getString("state").equals("1")){
                                toastShort("提交成功！");
                                finish();
                            }else {toastShort("提交失败！");}
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }

            @Override
            public void requestFailure(String message) {

            }
        },String.class);


    }

    @Override
    public void initData() {
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id", "");
        roleId = mm.getString("roleid","");
        version = mm.getString("version","");
        checkId = getIntent().getExtras().getString("checkId");
        activate();

    }
    private void activate(){
        Map<String,String> map = new HashMap<>();
        map.put("checkId",checkId);
        map.put("id",id);

        map.put("source", Since_case.set().getSource());

        HttpOkHttp.getInstance().requestPost(url, map, new HttpOkHttp.OkHttpCallBack<String>() {

            @Override
            public void requestSuccess(final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        check.clear();
                        Log.i("12123123",s);
                        if (s.equals("[]")){
                            toastShort("无盘点详情");
                            return;
                        }
                        Gson gson = new Gson();
                        List<Check_item_bean> userList = gson.fromJson(s, new TypeToken<List<Check_item_bean>>(){}.getType());
                        for(int i = 0;i < userList.size();i++){
                            check.add(new Check_item_bean(userList.get(i).getCheckdetailId(),userList.get(i).getType(),userList.get(i).getDeptId(),userList.get(i).getResult(),userList.get(i).getPlannum(),userList.get(i).getRealitynum(),userList.get(i).getAssetNumber()));
                        }
                        Check_Adapter check_adapter = new Check_Adapter(Check_Item.this,R.layout.check_item,check);
                        checklist.setAdapter(check_adapter);
                    }
                });

            }

            @Override
            public void requestFailure(String message) {

            }
        },String.class);
    }

    @Override
    public void onDismiss(Object o) {

    }

    @Override
    public void onBackPressed() {
        new AlertView(" 提示！", "是否退出！！！", "取消",new String[]{"确定"}, null, Check_Item.this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                //取消：position=-1,确定 position=0
                if (position==0){
                    finish();
                }
                if (position==-1){
                    return;
                }
            }
        }).setCancelable(true).setOnDismissListener(Check_Item.this).show();
    }
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Check_Item.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check_Item.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Check_Item.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check_Item.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Check_Item.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check_Item.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check_Item.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            //property_one.setText(scanResult);
            for (int i = 0; i<check.size();i++){
                if (scanResult.equals(check.get(i).getAssetNumber())){
                    Toast.makeText(Check_Item.this, "您扫描的是"+check.get(i).getType()+",请填写实际数量", Toast.LENGTH_LONG).show();
                    checklist.setSelection(i);
                    return;
                }
            }
            Toast.makeText(Check_Item.this, "此物资不在盘点计划中", Toast.LENGTH_LONG).show();


        }
    }
}
